from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from users.utils import merge_cookie_redis_cart
from .models import User
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from . import serializers


# 檢查重名
class CheckUsernameViews(APIView):
    def get(self,request,username):
        # 根據用戶名查詢用戶數量
        count = User.objects.filter(username=username).count()

        # 返回響應
        data = {
            "count":count
        }
        return Response(data=data,status=status.HTTP_200_OK)


#判斷手機號的存在性
class CheckMobileViews(APIView):
    def get(self,request,mobile):
        # 根據手機號查詢手機號數量
        count = User.objects.filter(mobile=mobile).count()

        # 返回響應
        data = {
            "count":count
        }
        return Response(data=data,status=status.HTTP_200_OK)


# 注冊用戶
class RegisterUserViews(CreateAPIView):
    serializer_class = serializers.RegisterUserSerializer


# 用戶中心展示
class UserInfoView(RetrieveAPIView):
    serializer_class = serializers.UserInfoSerializer

    permission_classes = [IsAuthenticated]  # 用戶認證

    def get_object(self):
        return self.request.user


# 發送郵件
class EmailSendView(UpdateAPIView):
    serializer_class = serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# 驗證激活郵箱
class VerificationEmailView(APIView):
    def get(self,request):
        # 獲取參數,並判斷
        token = request.query_params.get('token')
        if not token:
            return Response({"message":"缺少token"},status=status.HTTP_400_BAD_REQUEST)

        # 獲取token中的id,email,查詢用戶,並判斷是否存在
        user = User.check_verify_email_token(token)
        if not user:
            return Response({"message":"無效鏈接"},status=status.HTTP_400_BAD_REQUEST)
        else:
            # 修改狀態
            user.email_active = True
            user.save()

        # 返回響應
        return Response({"message":"OK"})


# 用戶地址
class AddressView(mixins.DestroyModelMixin,mixins.UpdateModelMixin,mixins.CreateModelMixin,GenericViewSet):
    serializer_class = serializers.AddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # 展示地址列表
    def list(self,request):
        # 獲取用戶登陸信息
        queryset = self.get_queryset()

        # 獲取序列化器
        serializer = self.get_serializer(instance=queryset,many=True)

        # 返回
        return Response({
            "addresses":serializer.data,
            "limit":20,
            "default_address_id":request.user.default_address_id
        })

    # 重寫地址創建方法,判斷用戶地址是否達到20個
    def create(self, request, *args, **kwargs):
        # 獲取用戶地址數量
        count = request.user.addresses.filter(is_deleted=False).count()

        # 判斷地址的數量
        if count >= 20:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 調用父類方法即可
        return super(AddressView,self).create(request,*args,**kwargs)

    # 設置默認地址
    @action(methods=['put'],detail=True)
    def status(self,request,pk):
        request.user.default_address_id = pk
        request.user.save()
        return Response(status=status.HTTP_200_OK)


    # 修改地址標題
    @action(methods=["put"],detail=True)
    def title(self,request,pk):
        # 獲取數據
        dict_data = request.data
        address = self.get_object()

        # 創建序列化器
        serializer = serializers.AddressTitleSerializer(instance=address,data=dict_data)

        # 校驗數據,入庫
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 返回響應
        return Response(serializer.data)


    # 重寫destroy方法,爲了邏輯刪除地址
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)


# 用戶瀏覽商品記錄
class UserBrowerHistoryView(CreateAPIView):
    serializer_class = serializers.UserBrowerHistorySerializer

    # def post(self, request, *args, **kwargs):
    #
    #     # 獲取參數
    #     dict_data = request.data
    #
    #     # 獲取序列化器,校驗
    #     serializer = self.get_serializer(data=dict_data)
    #     serializer.is_valid(raise_exception=True)
    #
    #     # 入庫(保存到redis)
    #     serializer.save()
    #
    #     # 返回
    #     return Response(serializer.data)
    def get(self,request):
        # 獲取redis中的數據
        redis_conn = get_redis_connection("history")
        sku_ids = redis_conn.lrange("history_%s"%request.user.id,0,4)

        # 拼接數據
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_dict = {
                "default_image_url":sku.default_image_url,
                "name":sku.name,
                "price":sku.price,
                "comments":sku.comments,
                "id":sku.id
            }
            sku_list.append(sku_dict)

        return Response(sku_list)


# 重寫登陸方法,合並購物車
class UserObtainJSONWebToken(ObtainJSONWebToken):

    def post(self, request, *args, **kwargs):
        # 調用父類方法
        response = super().post(request,*args,**kwargs)

        # 獲取序列化器
        serializer = self.get_serializer(data=request.data)

        # 判斷是否認證成功
        if serializer.is_valid():

            # 獲取user對象
            user = serializer.validated_data.get("user")

            # 合並購物車
            response = merge_cookie_redis_cart(request,user,response)

        return response

